import { ICodeRow, ICodeTableData } from '@preload/types';

export const NUMBER_FILTER = [
  
  {
    label: '1',
    value: '1'
  },
  {
    label: '2',
    value: '2'
  },
  {
    label: '3',
    value: '3'
  },
  {
    label: '4',
    value: '4'
  },
  {
    label: '5+',
    value: '5'
  },
  {
    label: '全部',
    value: '0'
  }
];

export const SEPARATORS = [
  {
    label: 'Tab',
    value: '\t'
  },
  {
    label: '空格',
    value: ' '
  },
  {
    label: ',',
    value: ','
  }
];


export class CodeTable{
  changedCodeRowSet: Set<ICodeRow> = new Set(); // 改变的行，更新后清空
  selectedLength: number = 0;
  codeSeparator: typeof SEPARATORS[number]['value'] = ' '; // 编码分隔符
  separator: typeof SEPARATORS[number]['value'] = '\t'; // 分隔符
  numFilter: typeof NUMBER_FILTER[number]['value'] = '0'; // 分隔符
  
  constructor( public data: ICodeTableData ){
  }
  
  get changedRowLength(){
    return this.changedCodeRowSet.size;
  }
  
  get length(){
    return this.data.codeRows.length;
  }
  
  get errLength(){
    return this.data.codeRows.reduce( ( count, codeRow ) => count + ( codeRow.originalSeparator !== this.separator ? 1 : 0 ), 0 );
  }
  
  update(){
    return new Promise( ( resolve, reject ) => {
      // {lineIndex: 13, text: '词', code: 'sss', weight: '20', stem: ''}
      // {rowType: 0, originalRow: ''}
      // ['text', 'code', 'weight', 'stem']
      const {
              filePath,
              codeRows,
              content
            } = this.data;
      for( let {
                 lineIndex,
                 text,
                 code,
                 weight, // 权重在页面中已有限制输入
                 stem
               } of codeRows )
      {
        // 将codeRow转换为string，替换到originalRow
        const formatedCode = code.replace( /[ ,\t]+/g, this.codeSeparator ).replace( /[\d\u4e00-\u9fff]/g, '' ).trim(); // 删除其中的数字、中文字符
        const formatedStem = stem.replace( /[ ,\t]+/g, this.codeSeparator ).replace( /[\d\u4e00-\u9fff]/g, '' ).trim();
        const formatedText = text.replace( /[ ,\t]+/g, '' ); // 删除词中错误的分割符
        content[ lineIndex ].originalRow = `${ formatedText }${ this.separator }${ formatedCode }${ this.separator }${ weight }${ this.separator }${ formatedStem }`.trim();
      }
      const lines = content.map( ( { originalRow } ) => originalRow );
      window.api.saveDict( filePath, lines ).then( () => {
        resolve( '' );
      } ).catch( ( err ) => {
        reject( err );
      } );
    } );
  }
}
